from library_system.data_manager import DataManager
from library_system.models import Student,Book
from library_system.data_nodes import LinkedList, Node

class CLI:
    def __init__(self):
        self.data_manager = DataManager()
        self.books = self.data_manager.load_books()
        self.students = {}
    def display_menu(self):
        print("\n=== Library Management System ===")
        print("0. Help")
        print("1. Register Student")
        print("2. Borrow Book")
        print("3. Return Book")
        print("4. Report Lost Book")
        print("5. Search Books")
        print("6. Add New Book")
        print("7. Reserve Book")
        print("8. View Most Borrowed Books")
        print("9. Display All Books")
        print("10. Exit")

    def register_student(self, student_id):
        if student_id not in self.students:
            self.students[student_id] = Student(student_id)
            print(f"Student {student_id} registered successfully.")
        else:
            print("Error: Student already registered.")

    def borrow_book(self, student_id, book_title):
        book = self.find_book_by_title(book_title)
        if not book:
            print("Error: Book not found.")
            return

        student = self.students.get(student_id)
        if not student:
            print("Error: Student not registered.")
            return

        if len(student.borrowed_books) >= 7:
            print("Error: Borrowing limit reached (maximum 7 books).")
            return

        if book_title in student.borrowed_books:
            print("Error: Book already borrowed.")
            return

        if student.add_book(book_title):
            book.increment_borrowed_count()
            print(f"Success: Book '{book_title}' borrowed.")
        else:
            print("Error: Failed to borrow book.")

    def return_book(self, student_id, book_title):
        book = self.find_book_by_title(book_title)
        if not book:
            print("Error: Book not found.")
            return

        student = self.students.get(student_id)
        if not student:
            print("Error: Student not registered.")
            return

        if student.remove_book(book_title):
            if book.waiting_list:
                next_student = book.waiting_list.pop(0)
                self.students[next_student].add_book(book_title)
                print(f"Success: Book '{book_title}' returned and assigned to waiting student {next_student}.")
            else:
                print(f"Success: Book '{book_title}' returned.")
        else:
            print("Error: Book not borrowed by this student.")
    
    def report_loss(self, student_id, book_title):
    # 查找目标书籍
        book = self.find_book_by_title(book_title)
        if not book:
            print("Error: Book not found.")
            return

        # 检查学生是否已注册
        student = self.students.get(student_id)
        if not student:
            print("Error: Student not registered.")
            return

        # 检查学生是否已借阅该书
        if book_title not in student.borrowed_books:
            print("Error: Book not borrowed by this student.")
            return

        # 更新书籍的遗失记录
        book.report_loss(student_id)

        # 从学生的借阅清单中移除该书
        student.remove_book(book_title)

        # 扣除学生的信用积分
        if student.deduct_credit():
            print(f"Success: Loss of book '{book_title}' reported. Credit score updated.")
        else:
            print("Warning: Cannot deduct credit (credit score already 0).")

        # 保存更改到文件
        self.data_manager.save_books(self.books)

    
    def search_books(self, keyword=None, author=None, year=None):
        results = []
        for book in self.books:
            if keyword and keyword.lower() in [k.lower() for k in book.keywords]:
                results.append(book)
            elif author and author.lower() in [a.lower() for a in book.authors]:
                results.append(book)
            elif year and str(book.year) == str(year):
                results.append(book)
        if results:
            print("Search Results:")
            for book in results:
                print(f"- Title: {book.title}, Authors: {', '.join(book.authors)}, Year: {book.year}")
        else:
            print("Error: No matching books found.")

    def add_new_book(self, title, authors, year, category, sub_category, language, page_count, keywords, summary, publisher):
        new_book = Book(
            title=title,
            authors=authors.split(","),
            year=int(year),
            category=category,
            sub_category=sub_category,
            language=language,
            page_count=int(page_count),
            keywords=keywords.split(","),
            summary=summary,
            publisher=publisher
        )
        self.books.append(new_book)
        self.data_manager.save_books(self.books)
        print(f"Success: New book '{title}' added to the library.")

    def reserve_book(self, student_id, book_title):
        book = self.find_book_by_title(book_title)
        if not book:
            print("Error: Book not found.")
            return

        student = self.students.get(student_id)
        if not student:
            print("Error: Student not registered.")
            return

        if book_title in student.borrowed_books:
            print("Error: You have already borrowed this book.")
            return

        book.add_to_waiting_list(student_id)
        print(f"Success: Book '{book_title}' reserved. You are on the waiting list.")
        self.data_manager.save_books(self.books)#!!

    def find_book_by_title(self, title):
        for book in self.books:
            if book.title == title:
                return book
        return None

    def get_most_borrowed_books(self, top_n=5):
        sorted_books = sorted(self.books, key=lambda x: x.borrowed_count, reverse=True)
        print("Most Borrowed Books:")
        for book in sorted_books[:top_n]:
            print(f"- Title: {book.title}, Borrowed Count: {book.borrowed_count}")

    def display_all_books(self):
        if not self.books:
            print("Error: No books available in the library.")
            return
        print("\n=== Library Catalog ===")
        for book in self.books:
            print(f"- Title: {book.title}")
            print(f"  Authors: {', '.join(book.authors)}")
            print(f"  Year: {book.year}")
            print(f"  Category: {book.category} > {book.sub_category}")
            print(f"  Language: {book.language}")
            print(f"  Borrowed Count: {book.borrowed_count}")
            print(f"  Waiting List: {', '.join(book.waiting_list) if book.waiting_list else 'None'}")
            print(f"  Loss Records: {', '.join(book.loss_records) if book.loss_records else 'None'}")
            print("-" * 40)
    def display_help(self):
        print("\n=== Help Menu ===")
        print("0. Help: Display this help menu.")
        print("1. Register Student: Register a new student with a unique ID.")
        print("2. Borrow Book: Borrow a book using your student ID and the book title.")
        print("3. Return Book: Return a borrowed book using your student ID and the book title.")
        print("4. Report Lost Book: Report a lost book and update your credit score.")
        print("5. Search Books: Search for books by keyword, author, or year.")
        print("6. Add New Book: Add a new book to the library catalog.")
        print("7. Reserve Book: Reserve a book that is currently unavailable.")
        print("8. View Most Borrowed Books: View the most frequently borrowed books.")
        print("9. Display All Books: Display a list of all books in the library.")
        print("10. Exit: Exit the program.")
    
    def find_book_by_title(self, title):
        for book in self.books:
            if book.title == title:
                return book
        print(f"Error: Book '{title}' not found in the library.")
        return None

    def run(self):
        print("Welcome to the Library Management System!")
        print("Please select an option from the menu below.")
        while True:
            self.display_menu()
            try:
                choice = int(input("Enter your choice (0-10): "))
                if choice == 0:
                    self.display_help()
                elif choice == 1:
                    student_id = input("Enter student ID: ")
                    self.register_student(student_id)
                elif choice == 2:
                    student_id = input("Enter student ID: ")
                    book_title = input("Enter book title: ")
                    self.borrow_book(student_id, book_title)
                elif choice == 3:
                    student_id = input("Enter student ID: ")
                    book_title = input("Enter book title: ")
                    self.return_book(student_id, book_title)
                elif choice == 4:
                    student_id = input("Enter student ID: ")
                    book_title = input("Enter book title: ")
                    self.report_loss(student_id, book_title)
                elif choice == 5:
                    keyword = input("Enter keyword (optional): ")
                    author = input("Enter author (optional): ")
                    year = input("Enter year (optional): ")
                    self.search_books(keyword or None, author or None, year or None)
                elif choice == 6:
                    title = input("Enter title: ")
                    authors = input("Enter authors (comma-separated): ")
                    year = input("Enter year: ")
                    category = input("Enter category: ")
                    sub_category = input("Enter sub-category: ")
                    language = input("Enter language: ")
                    page_count = input("Enter page count: ")
                    keywords = input("Enter keywords (comma-separated): ")
                    summary = input("Enter summary: ")
                    publisher = input("Enter publisher: ")
                    self.add_new_book(title, authors, year, category, sub_category, language, page_count, keywords, summary, publisher)
                elif choice == 7:
                    student_id = input("Enter student ID: ")
                    book_title = input("Enter book title: ")
                    self.reserve_book(student_id, book_title)
                elif choice == 8:
                    self.get_most_borrowed_books()
                elif choice == 9:
                    self.display_all_books()
                elif choice == 10:
                    confirm = input("Are you sure you want to exit? (yes/no): ").strip().lower()
                    if confirm == "yes":
                        print("Exiting the system. Goodbye!")
                        break
                    else:
                        print("Exit canceled. Returning to the main menu.")
                else:
                    print("Error: Invalid choice. Please select a number between 0 and 10.")
            except ValueError:
                print("Error: Please enter a valid number.")

    
    